<template>
    <div class="admin-second-category">
        <div class="admin-second-header">产品二级分类</div>
        <div class="admin-second-content">
            <span><el-button type="primary" @click="openDialogVisibleAdd">新增</el-button></span>
            <div>
                <el-table v-loading="loading" :data="secondCategoryData" style="width: 100%">
                    <el-table-column type="index" />
                    <el-table-column prop="title" label="中文标题" width="180" />
                    <el-table-column prop="title_en" label="英文标题" width="180" />
                    <el-table-column prop="first_category.title" label="一级中文标题" width="180" />
                    <el-table-column prop="first_category.title_en" label="一级英文标题" width="180" />
                    <el-table-column label="图片">
                        <template v-slot:default="scope">
                            <img :src="scope.row.img + '?x-oss-process=image/resize,h_80/quality,q_50'">
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot:default="scope">
                            <el-button type="danger" :icon="Delete" circle
                                @click="deleteSecondCategory(scope.row.id)" />
                            <el-button type="primary" :icon="Edit" circle @click="updateSecondCategory(scope.row)" />
                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin-top: 20px;">
                    <el-pagination 
                        background 
                        :page-size="currentSize"
                        layout="prev, pager, next" 
                        :total="productTotal" 
                        @current-change="changePage" 
                        v-model:current-page="currentPage" 
                    />
                </div> 
            </div>
        </div>
        <!-- 新增二级分类 -->
        <el-dialog v-model="dialogVisibleAdd" title="新增二级分类" width="450" :before-close="handleClose">
            <el-form :model="formSecondCategory" label-width="auto" style="max-width: 400px">
                <el-form-item label="标题（中文）">
                    <el-input v-model="formSecondCategory.title" />
                </el-form-item>
                <el-form-item label="标题（英文）">
                    <el-input v-model="formSecondCategory.title_en" />
                </el-form-item>
                <div style="margin-bottom: 10px;">
                    <span style="margin-right: 30px;">关联一级</span>
                    <el-select v-model="firstCategory" value-key="id" placeholder="Select" style="width: 312px"
                        @change="bindValue">
                        <el-option v-for="item in firstCategoryData" :key="item.id" :label="item.title" :value="item" />
                    </el-select>
                </div>
                <div style="text-align: center; padding: 10px; width: 400px;">
                    <div style="max-width: 400px; margin-bottom: 30px;">
                        <el-alert title="建议上传图片参考大小： 238px * 180px" type="warning" show-icon :closable="false"/>
                    </div>
                    <el-upload class="avatar-uploader" :action="uploadUrl"
                        :show-file-list="false" :headers="headersAdmin" :on-success="handleSecondImgSuccess"
                        style="width: 400px;">
                        <img v-if="formSecondCategory.img"
                            :src="formSecondCategory.img + '?x-oss-process=image/resize,h_100/quality,q_50'"
                            class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </div>
            </el-form>
            <div style="text-align: center; margin-top: 20px;"><el-button type="primary"
                    @click="onSubmitAddSecondCategory">新增</el-button></div>
        </el-dialog>
        <!-- 更新数据 -->
        <el-dialog v-model="dialogVisibleUpdate" title="更新二级分类" width="450" :before-close="handleCloseUpdate">
            <el-form :model="formSecondCategory" label-width="auto" style="max-width: 400px;">
                <el-form-item label="标题（中文）">
                    <el-input v-model="formSecondCategory.title" />
                </el-form-item>
                <el-form-item label="标题（英文）">
                    <el-input v-model="formSecondCategory.title_en" />
                </el-form-item>
                <div style="margin-bottom: 10px;">
                    <span style="margin-right: 30px;">关联一级</span>
                    <el-select v-model="firstCategory" value-key="id" placeholder="Select" style="width: 312px"
                        @change="bindValue">
                        <el-option v-for="item in firstCategoryData" :key="item.id" :label="item.title" :value="item" />
                    </el-select>
                </div>
                <div style="text-align: center; padding: 10px; width: 400px;">
                    <div style="max-width: 400px; margin-bottom: 30px;">
                        <el-alert title="建议上传图片参考大小： 238px * 180px" type="warning" show-icon :closable="false"/>
                    </div>
                    <el-upload class="avatar-uploader" :action="uploadUrl"
                        :show-file-list="false" :headers="headersAdmin" :on-success="handleSecondImgSuccess"
                        style="width: 400px;">
                        <img v-if="formSecondCategory.img"
                            :src="formSecondCategory.img + '?x-oss-process=image/resize,h_100/quality,q_50'"
                            class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </div> 
            </el-form>
            <div style="text-align: center; margin-top: 20px;"><el-button type="primary"
                    @click="onSubmitUpdateSecondCategory">更新</el-button></div>
        </el-dialog>
        <!-- 删除确认 -->
        <el-dialog v-model="deleteSecondCategoryDialog" title="删除二级分类" width="500" align-center>
            <span>请确认此二级产品分类下是否还存在产品，否则会影响产品列表的正常显示</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="onSubmitDeleteSecondCategoryCancle">取消</el-button>
                    <el-button type="danger" @click="onSubmitSecondFirstCategory">
                        删除
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Delete, Edit } from '@element-plus/icons-vue';
import { addSecondCategory, listSecondCategory, listFirstCategory, delSecondCategory, delOssImg } from '../../requests/index';
import { uploadUrl, uploadEditUrl } from '@/utils/request';
const loading = ref(true);
const firstCategoryData = ref([]);
const secondCategoryData = ref([]);
const productTotal = ref(0);
const currentPage =  ref(1);
const currentSize = ref(5)
const firstCategory = ref();
const token = window.localStorage.getItem("token");
const headersAdmin = {
    Authorization: `Bearer ${token}`
};
const dialogVisibleAdd = ref(false);
const formSecondCategory = reactive({
    id: null,
    title: "",
    title_en: "",
    img: "",
    firstCategoryId: null
});
const deleteSecondCategoryDialog = ref(false);
const dialogVisibleUpdate = ref(false);
// 获取一级分类列表用于二级分类父级
const getfirstCategoryData = async () => {
    const res = await listFirstCategory();
    if (res.status === 2000) {
        firstCategoryData.value = res.data;
    } else {
        ElMessage.error("获取一级分类失败")
    }
};
// 打开新增二级分类的对话窗
const openDialogVisibleAdd = () => {
    getfirstCategoryData();
    dialogVisibleAdd.value = true;
}
// 关闭新增二级分类的对话框
const closeDialogVisibleAdd = () => {
    formSecondCategory.id = null;
    formSecondCategory.title = "";
    formSecondCategory.title_en = "";
    formSecondCategory.img = "";
    formSecondCategory.firstCategoryId = null;
    firstCategory.value = null;
    dialogVisibleAdd.value = false;
};
// 当select变化时
const bindValue = (value) => {
    formSecondCategory.firstCategoryId = value.id;
}
// 提交新增二级分类
const onSubmitAddSecondCategory = async () => {
    const res = await addSecondCategory(formSecondCategory);
    if (res.status === 2000) {
        ElMessage({
            message: "创建二级分类成功！",
            type: 'success'
        });
        closeDialogVisibleAdd();
        getSecondCategory();
    } else {
        ElMessage.error("创建二级分类失败")
    }
};
// 获取二级分类列表
const getSecondCategory = async () => {
    loading.value = true;
    const res = await listSecondCategory({"page": currentPage.value, "size": currentSize.value});
    if (res.status === 2000) {
        secondCategoryData.value = res.data;
        productTotal.value = res.total;
    } else {
        ElMessage.error("获取二级分类列表失败")
    };
    loading.value = false;
};
// 进入页面执行
getSecondCategory();
// 分页
const changePage = async()=>{
    loading.value = true;
    const res = await listSecondCategory({"page": currentPage.value, "size": currentSize.value});
    if (res.status === 2000){
        secondCategoryData.value = res.data;
        productTotal.value = res.total;
    }else{
        ElMessage.error("获取二级分类列表失败")
    };
    loading.value = false;
}

const resetFormSecond = ()=>{
    formSecondCategory.id = null;
    formSecondCategory.title = "";
    formSecondCategory.title_en = "";
    formSecondCategory.img = "";
    formSecondCategory.firstCategoryId = 0;
};


const handleClose = () => {
    resetFormSecond();
    dialogVisibleAdd.value = false;
};

// 上传图片
const handleSecondImgSuccess = async(response, uploadFile) => {
    if (response.status === 2000) {
        // 判断原 formSecondCategory.img 是否有值，如果有值则删除
        if (formSecondCategory.img){
            const res = await delOssImg({"img":formSecondCategory.img});
        }
        formSecondCategory.img = response.file;
    } else {
        ElMessage.error(response.msg);
    }
};
// 打开确认删除记录框
const deleteSecondCategory = (id) => {
    formSecondCategory.id = id;
    deleteSecondCategoryDialog.value = true;
}
// 取消删除记录
const onSubmitDeleteSecondCategoryCancle = () => {
    resetFormSecond();
    deleteSecondCategoryDialog.value = false;
};
// 删除二级分类
const onSubmitSecondFirstCategory = async (id) => {
    const res = await delSecondCategory({ "id": formSecondCategory.id });
    if (res.status === 2000) {
        ElMessage.success("删除成功");
        getSecondCategory();
    } else {
        ElMessage.error("删除失败")
    };
    onSubmitDeleteSecondCategoryCancle();
};

// 打开更新二级分类对话框
const updateSecondCategory = (row) => {
    getfirstCategoryData();
    dialogVisibleUpdate.value = true;
    formSecondCategory.id = row.id;
    formSecondCategory.title = row.title;
    formSecondCategory.title_en = row.title_en;
    formSecondCategory.img = row.img;
    formSecondCategory.firstCategoryId = row.first_category.id;
    firstCategory.value = row.first_category.title;
};
// 提交更新二级分类
const onSubmitUpdateSecondCategory = async() => {
    const res = await addSecondCategory(formSecondCategory);
    if (res.status === 2000) {
        ElMessage.success("更新二级分类成功！")
        handleCloseUpdate();
        getSecondCategory();
    } else {
        ElMessage.error("更新二级分类失败")
    }
};
// 关闭二级分类对话框
const handleCloseUpdate = () => {
    resetFormSecond();
    dialogVisibleUpdate.value = false;
};

</script>

<style scoped>
.admin-second-header {
    margin-top: 20px;
    margin-left: 20px;
    height: 40px;
    line-height: 40px;
    background-color: #F9F9F9;
    padding: 0 20px;
}

.admin-second-content {
    margin-top: 10px;
    margin-bottom: 50px;
    margin-left: 20px;
}

.admin-second-category {
    min-height: 100px;
}
</style>